import 'package:cloud_medicine/components/shop_picture.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/shop_api.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:cloud_medicine/model/order_list.dart';
import 'package:cloud_medicine/pages/order_info.dart';
import 'package:cloud_medicine/pages/shop_detail.dart';
import 'package:cloud_medicine/pages/shop_grade.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class OrderList extends StatefulWidget {
  OrderList({Key key}) : super(key: key);

  @override
  _OrderListState createState() => _OrderListState();
}

class _OrderListState extends State<OrderList> with TickerProviderStateMixin {
  TabController _controller;
  @override
  void initState() {
    super.initState();
    //设置三个按钮
    _controller = TabController(length: 5, vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  List<Widget> _tabs = [
    Tab(
      text: '全部',
    ),
    Tab(
      text: '已下单',
    ),
    Tab(
      text: '配送中',
    ),
    Tab(
      text: '已送达',
    ),
    Tab(
      text: '已完成',
    )
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      appBar: AppBar(
        title: Text('我的订单'),
        centerTitle: true,
        bottom: TabBar(
          controller: _controller,
          tabs: _tabs,
          isScrollable: true,
        ),
      ),
      body: TabBarView(
        controller: _controller,
        children: <Widget>[
          OrderListBody(id: 0),
          OrderListBody(id: 1),
          OrderListBody(id: 2),
          OrderListBody(id: 3),
          OrderListBody(id: 4),
        ],
      ),
    );
  }
}

class OrderListBody extends StatefulWidget {
  final int id;
  OrderListBody({Key key, this.id}) : super(key: key);

  @override
  _OrderListBodyState createState() => _OrderListBodyState();
}

class _OrderListBodyState extends State<OrderListBody> {
  bool _loading = false;
  List<OrderItem> orderList = [];
  bool apiDataIsNull = false;
  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });

    dynamic res = await getOrderList_api(
        '$backIP/shop/orderList', {'status': widget.id}); //接口路径
    if (res['data'] != null) {
      res['data'].forEach((dynamic orderItem) {
        OrderItem orderItemModel = OrderItem.init(orderItem);
        orderList.add(orderItemModel);
      });
    } else {
      setState(() {
        apiDataIsNull = true;
      });
    }

    if (mounted) {
      setState(() {
        _loading = false;
      });
    }
    return;
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Map<int, String> _orderStatus = {1: '已下单', 2: '配送中', 3: '已送达', 4: '已完成'};

  Widget _childLayout() {
    if (user == null) {
      Fluttertoast.showToast(
        msg: '请先登录',
        backgroundColor: Colors.black,
        textColor: Colors.white,
      );
      return null;
    } else if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      if (apiDataIsNull) {
        return Center(
          child: Text('还没有订单哦~'),
        );
      } else {
        return ListView.builder(
            itemCount: orderList.length,
            itemBuilder: (context, index) {
              return Material(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(12),
                  child: Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(top: 10),
                    padding: EdgeInsets.all(10),
                    child: Column(
                      children: [
                        GestureDetector(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Text(
                                    orderList[index].shop.name,
                                    style: TextStyle(fontSize: 19),
                                  ),
                                  Icon(Icons.chevron_right),
                                ],
                              ),
                              Container(
                                child: Text(
                                    '${_orderStatus[orderList[index].id]}'),
                              )
                            ],
                          ),
                          onTap: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => ShopDetail(
                                      shopid: orderList[index].shop.id,
                                    )));
                          },
                        ),
                        Divider(
                          thickness: 1,
                          color: Colors.grey[300],
                        ),
                        InkWell(
                          splashColor: Colors.yellow.withOpacity(0.3),
                          highlightColor: Colors.yellow.withOpacity(0.1),
                          child: Row(
                            children: [
                              Container(
                                child: ShopImg(
                                  imgUrl: orderList[index].shop.image,
                                  imageStyle: 60,
                                ),
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    margin:
                                        EdgeInsets.only(left: 10, bottom: 5),
                                    child: Text(
                                      '下单时间:${orderList[index].time}',
                                      style: TextStyle(
                                          color: Colors.grey[600],
                                          fontSize: 13),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(left: 10),
                                    child: Text(
                                      '总价:￥${orderList[index].allPrice}',
                                      style: TextStyle(
                                          color: Colors.grey[600],
                                          fontSize: 13),
                                    ),
                                  )
                                ],
                              ),
                              _isGrade(
                                  orderList[index].id, orderList[index].orderID)
                            ],
                          ),
                          onTap: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => OrderInfo(
                                      shopid: orderList[index].shop.id,
                                      shopname: orderList[index].shop.name,
                                      shopimage: orderList[index].shop.image,
                                      orderID: orderList[index].orderID,
                                    )));
                          },
                        )
                      ],
                    ),
                  ));
            });
      }
    }
  }

  _isGrade(num status, num id) {
    if (user.identify.id != 5) {
      if (_orderStatus[status] == '已送达') {
        return Container(
            margin: EdgeInsets.only(top: 10, left: 10),
            child: GestureDetector(
              child: Chip(
                label: Text(
                  '去打分',
                  style: TextStyle(color: Colors.white),
                ),
                backgroundColor: Colors.yellow[700],
              ),
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (BuildContext context) => ShopGrade(
                          orderid: id,
                        )));
              },
            ));
      } else if (_orderStatus[status] == '已完成' ||
          _orderStatus[status] == '已下单') {
        return Container();
      } else {
        return Container(
            margin: EdgeInsets.only(top: 10, left: 10),
            child: GestureDetector(
              child: Chip(
                label: Text(
                  '去收货',
                  style: TextStyle(color: Colors.white),
                ),
                backgroundColor: Colors.yellow[700],
              ),
              onTap: () {
                openAlertDialog(context, () {
                  _changeStatus(id, status);
                }, '确认收货吗？一旦确认，无法撤销');
              },
            ));
      }
    } else {
      if (_orderStatus[status] == '已下单') {
        return Container(
            margin: EdgeInsets.only(top: 10, left: 10),
            child: GestureDetector(
              child: Chip(
                label: Text(
                  '已配送',
                  style: TextStyle(color: Colors.white),
                ),
                backgroundColor: Colors.yellow[700],
              ),
              onTap: () {
                openAlertDialog(context, () {
                  _changeStatus(id, status);
                }, '确认已配送吗？状态将传给用户');
              },
            ));
      } else {
        return Container();
      }
    }
  }

  Future _changeStatus(num id, num status) async {
    await editOrderStatus_api(
        '$backIP/shop/orderstatus', {'current_status': status, 'ID': id});
  }

  @override
  Widget build(BuildContext context) {
    return _childLayout();
  }
}
